// This file contains code that we reuse between our tests.
import * as path from 'node:path'
import * as test from 'node:test'
const helper = require('fastify-cli/helper.js')

// Set test environment variables
process.env.NODE_ENV = 'test'
process.env.REDIS_IN_MEMORY = 'true'
process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret-key-for-testing-only'
process.env.JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d'

export type TestContext = {
    after: typeof test.after
}

const AppPath = path.join(__dirname, '..', 'src', 'app.ts')

// Fill in this config with all the configurations
// needed for testing the application
function config() {
    return {
        skipOverride: true // Register our application with fastify-plugin
    }
}

// Automatically build and tear down our instance
async function build(t: TestContext) {
    // you can set all the options supported by the fastify CLI command
    const argv = [AppPath]

    // fastify-plugin ensures that all decorators
    // are exposed for testing purposes, this is
    // different from the production setup
    const app = await helper.build(argv, config())

    // Tear down our app after we are done
    // eslint-disable-next-line no-void
    t.after(() => void app.close())

    return app
}

export { config, build }
